package com.sanxiau.dormitory.yang.service.impl;

import com.aliyuncs.CommonResponse;
import com.sanxiau.dormitory.yang.entity.LoginIn;
import com.sanxiau.dormitory.yang.face.FaceDetect;
import com.sanxiau.dormitory.yang.face.FaceSearch;
import com.sanxiau.dormitory.yang.mapper.LoginMapper;
import com.sanxiau.dormitory.yang.service.LoginService;
import com.sanxiau.dormitory.yang.util.MD5Util;
import com.sanxiau.dormitory.yang.util.SendSms;
import com.sanxiau.dormitory.yang.util.Verify;
import com.sanxiau.dormitory.yang.vo.ResultInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*登陆的Service层实现类代码*/
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    LoginMapper loginMapper;


    @Override
    public ResultInfo UserLogin1(String user_name, String user_pwd,String res) {
        ResultInfo resultInfo = new ResultInfo();
        int len = 6;
        String reg = "^[0-9a-zA-Z_]+$";

        if ("".equals(user_name) || null == user_name) {
            resultInfo.setMessage("请填写用户名");
        } else if ("".equals(user_pwd) || null == user_pwd) {
            resultInfo.setMessage("请填写密码");
        }else {
            // 字符串是否与正则表达式相匹配
            boolean rs = Pattern.matches(reg, user_name);
            boolean rs1 = Pattern.matches(reg, user_pwd);
            if ("false".equals(res)) {
                resultInfo.setMessage("验证码错误");
            } else if (user_pwd.length() < len) {
                resultInfo.setMessage("密码至少为6位");
            } else if (!rs) {
                resultInfo.setMessage("用户名只能由数字、字母或下划线组成");
            } else if (!rs1) {
                resultInfo.setMessage("密码只能由数字、字母或下划线组成");
            } else {
                String simpleHash = MD5Util.getPasswordByMD5(user_pwd, user_name);
                //获取当前用户
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(user_name, simpleHash);
                try {
                    subject.login(token);
                    resultInfo.setMessage("登陆成功");
                    LoginIn loginIn = loginMapper.userLogin(user_name, simpleHash);
                    if (null != loginIn) {
                        resultInfo.setId(loginIn.getUser_id());
                        resultInfo.setName(loginIn.getUser_name());
                        resultInfo.setTime(loginIn.getLogin_time());
                    }else {
                        resultInfo.setMessage("账号名或密码错误,请重新输入");
                    }
                } catch (UnknownAccountException e) {
                    resultInfo.setMessage("账号名或密码错误,请重新输入");
                } catch (IncorrectCredentialsException e) {
                    resultInfo.setMessage("账号名或密码错误,请重新输入");
                }
            }
        }
        return resultInfo;
    }

    @Override
    public ResultInfo UserLogin2(String tel, String verify,HttpSession session) {
        String verify1 = session.getAttribute(tel)+"";
        ResultInfo resultInfo = new ResultInfo();
        //System.out.println("verify1" + verify1);
        if (verify1!=null && !verify1.equals("")) {
            if (verify1.equals(verify)) {
                //resultInfo.setMessage("登陆成功");
                session.removeAttribute(tel);
                Subject subject = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(tel, "tel");
                try {
                    subject.login(token);
                    resultInfo.setMessage("登陆成功");
                    LoginIn loginIn = loginMapper.queryUserByTel(tel);
                    if (null != loginIn) {
                        resultInfo.setId(loginIn.getUser_id());
                        resultInfo.setName(loginIn.getUser_name());
                        resultInfo.setTime(loginIn.getLogin_time());
                    }else {
                        resultInfo.setMessage("手机号未注册，请重新输入");
                    }
                    /*resultInfo.setName(loginIn.getUser_name());
                    resultInfo.setPwd(loginIn.getUser_pwd());
                    //System.out.println(loginIn);
                    loginIn.setLogin_state("1");
                    loginIn.setLogin_time(new Date());
                    resultInfo.setId(loginIn.getUser_id());
                    resultInfo.setName(loginIn.getUser_name());
                    resultInfo.setTime(loginIn.getLogin_time());
                    //System.out.println(loginIn);
                    int num = loginMapper.updateUser(loginIn);
                    resultInfo.setMessage("登陆成功");*/
                    //System.out.println("num = " + num);
                    //System.out.println("短信验证登陆成功");
                }catch (Exception e){
                    resultInfo.setMessage("验证码过期或错误，请稍后重新发送");
                }
            } else {
                resultInfo.setMessage("验证码错误");
                System.out.println("验证码错误");
            }
        }else {
            resultInfo.setMessage("验证码过期或错误，请稍后重新发送");
            System.out.println("验证码过期或错误，请稍后重新发送");
        }
        return resultInfo;
    }

    @Override
    public ResultInfo SendVerify(String tel,HttpSession session) {
        LoginIn loginIn = loginMapper.queryUserByTel(tel);
        ResultInfo resultInfo = new ResultInfo();
        if (null != loginIn) {

            String verify1 = Verify.getVerify();
            session.setAttribute(tel, verify1);
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    session.removeAttribute(tel);
                }
            }, 60000);
            //System.out.println("验证码:" + verify1);
            CommonResponse response = null;
            try {
                response = SendSms.sendSms(tel, verify1);
            } catch (Exception e) {
                resultInfo.setMessage("验证码发送失败，请重新点击发送按钮");

            }
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(response.getData());
                System.out.println(jsonObject.get("Message"));
                if (jsonObject.get("Message").equals("OK")) {
                    resultInfo.setMessage("验证码发送成功，请注意查收");
                } else {
                    resultInfo.setMessage("验证码发送失败，请重新点击发送按钮");
                }

            } catch (JSONException e) {
                resultInfo.setMessage("验证码发送失败，请重新点击发送按钮");
                e.printStackTrace();

            }
        }else {
            resultInfo.setMessage("手机号未注册，请重新输入");
        }
        return resultInfo;
    }

    @Override
    public ResultInfo quit(String name,int id,HttpSession session) {
        ResultInfo resultInfo = new ResultInfo();
        LoginIn loginIn = new LoginIn();
        loginIn.setLogin_state("0");
        loginIn.setLogin_time(new Date());
        loginIn.setUser_id(id);
        //loginIn.setUser_name(session.getAttribute("userName")+"");
        //System.out.println(loginIn);
        int num = loginMapper.updateUser(loginIn);
        if (num > 0) {
            resultInfo.setMessage("退出成功");
        } else {
            resultInfo.setMessage("退出失败");
        }
        return resultInfo;
    }

    @Override
    public ResultInfo registerUser(LoginIn loginIn) {
        ResultInfo resultInfo = new ResultInfo();
        if (null != loginIn) {
            loginIn.setUser_pwd(MD5Util.getPasswordByMD5(loginIn.getUser_pwd(),loginIn.getUser_name()));
            loginIn.setState("2");
            loginIn.setRegister_time(new Date());
            loginIn.setLogin_state("0");
            int num = loginMapper.registerUser(loginIn);
            if (num > 0){
                resultInfo.setMessage("注册成功");
            }else {
                resultInfo.setMessage("注册失败，请重试");
            }
        }else {
            resultInfo.setMessage("请填写必要信息");
        }
        return resultInfo;
    }

    @Override
    public ResultInfo isExist(String user_name) {
        LoginIn loginIn = loginMapper.queryUserByName(user_name);
        ResultInfo resultInfo = new ResultInfo();
        if (null != loginIn){
            resultInfo.setIsexist(true);
        }else {
            resultInfo.setIsexist(false);
        }
        return resultInfo;
    }

  /*  @Override
    public ResultInfo UserLogin3(String base64Data) throws JSONException {
        ResultInfo resultInfo = new ResultInfo();
        int userid = -1;
        String jpg1 = FaceDetect.faceDetect(base64Data);
        JSONObject json0 = null;
        json0 = new JSONObject(jpg1);
        int error_code1 = json0.getInt("error_code");
        if (error_code1 > 0) {
            resultInfo.setMessage("采集失败,请重试");
            System.out.println("Detect采集失败,请重试");
        } else {
            String jpg = FaceSearch.faceSearch(base64Data);
            JSONObject json1 = new JSONObject(jpg);
            int error_code = json1.getInt("error_code");
            if (error_code > 0) {
                resultInfo.setMessage("验证失败,请重试");
                System.out.println("验证失败,请重试");
            } else {
                JSONObject json2 = (JSONObject) json1.get("result");
                JSONArray user_list = json2.getJSONArray("user_list");
                JSONObject user = (JSONObject) user_list.get(0);
                String user_id = user.getString("user_id");
                System.out.println("user_id = " + user_id);
                //System.out.println("******************"+jpg);
                userid = Integer.parseInt(user_id);
                resultInfo.setId(userid);
                resultInfo.setMessage("验证成功");
                System.out.println("验证成功");
            }
        }
        LoginIn loginIn = loginMapper.queryUserByID(userid);
        if (loginIn != null) {
            resultInfo.setMessage("登陆成功");
            loginIn.setLogin_state("1");
            loginIn.setLogin_time(new Date());
            resultInfo.setId(loginIn.getUser_id());
            resultInfo.setName(loginIn.getUser_name());
            resultInfo.setTime(loginIn.getLogin_time());
            System.out.println(loginIn);
            int num = loginMapper.updateUser(loginIn);
            System.out.println("num = " + num);
            System.out.println("人脸识别登陆成功");
            resultInfo.setId(userid);
        } else {
            resultInfo.setMessage("登陆失败");
            System.out.println("人脸识别登陆失败");
        }
        return resultInfo;
    }*/
}
